package com.north.light.libcommon.recyclerview;


import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import static androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_DRAGGING;
import static androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_IDLE;
import static androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_SETTLING;


/**
 * 下拉刷新，上拉加载更多recyclerview
 * 下拉刷新使用官方提供的swiperefreshlayout
 */
public class SwipeRecyclerView extends LinearLayout {
    private static final String TAG = SwipeRecyclerView.class.getName();
    //是否允许下拉刷新标识
    private volatile boolean mCanRefresh = true;
    private volatile boolean mCanLoadMore = true;
    private SwipeRefreshLayout mSwipeLayout;
    //内嵌recyclerview
    private RecyclerView mRecyclerView;
    //handler，消息发送
    private Handler mMessageHandler = new Handler(Looper.getMainLooper());
    // 最后几个完全可见项的位置（瀑布式布局会出现这种情况）
    private int[] lastVisiblePosition;
    // 最后一个完全可见项的位置
    private int lastItemPosition;
    //用户是否滑动过的标识
    private volatile boolean isScrollTAG = false;
    private OnScrollListener mScrollListener;
    private AutoLoadScrollListener mAutoLoadScrollListener;
    //父布局
    private LinearLayout mContentLayout;
    //    //下拉刷新布局
//    private LinearLayout mRefreshLayout;
    //加载更多布局
    private LinearLayout mLoadMoreLayout;
    //加载更多布局的高度
    private int loadMoreViewHeight = 0;
    //用户当前滑动是否上拉的标识
    private volatile boolean isDragLoadMore = false;
    private float mTouchY = 0;
    //页数标识
    private int curPage = 0;//当前页数
    //recyclerview item total count
    private int totalCount = 0;


    public SwipeRecyclerView(@NonNull Context context) {
        this(context, null);
    }

    public SwipeRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return super.onInterceptTouchEvent(ev);
    }

    @SuppressLint("ClickableViewAccessibility")
    private void init() {
        if (mSwipeLayout == null) {
            mSwipeLayout = new SwipeRefreshLayout(getContext());
            LayoutParams swipeP = new LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            mSwipeLayout.setLayoutParams(swipeP);
            this.addView(mSwipeLayout);
            this.mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    if (mScrollListener != null) {
                        setPage(0);
                        mScrollListener.refresh();
                    }
                }
            });
        }
        if (mContentLayout == null) {
            mContentLayout = new LinearLayout(getContext());
            SwipeRefreshLayout.LayoutParams contentP = new LayoutParams(
                    SwipeRefreshLayout.LayoutParams.MATCH_PARENT, SwipeRefreshLayout.LayoutParams.MATCH_PARENT);
            mContentLayout.setOrientation(LinearLayout.VERTICAL);
            mContentLayout.setLayoutParams(contentP);
            this.mSwipeLayout.addView(mContentLayout);
        }
//        //添加refresh layout
//        if (mRefreshLayout == null) {
//            mRefreshLayout = new LinearLayout(getContext());
//            LinearLayout.LayoutParams refreshP = new LinearLayout.LayoutParams(
//                    LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//            mRefreshLayout.setLayoutParams(refreshP);
//            mRefreshLayout.setOrientation(LinearLayout.VERTICAL);
//            this.mContentLayout.addView(mRefreshLayout);
//        }
        //动态添加recyclerview
        if (mRecyclerView == null) {
            mRecyclerView = new RecyclerView(getContext());
            LayoutParams recyP = new LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
            recyP.weight = 1;
            mRecyclerView.setLayoutParams(recyP);
            this.mContentLayout.addView(mRecyclerView);
            //滑动监听
            mAutoLoadScrollListener = new AutoLoadScrollListener();
            addOriginScrollListener(mAutoLoadScrollListener);
            mRecyclerView.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            mTouchY = event.getY();
                            break;
                        case MotionEvent.ACTION_MOVE:
                            if (mTouchY < event.getY()) {
                                isDragLoadMore = false;
                            } else {
                                isDragLoadMore = true;
                            }
                            break;
                    }
                    return false;
                }
            });
        }
        //添加load more layout
        if (mLoadMoreLayout == null) {
            mLoadMoreLayout = new LinearLayout(getContext());
            LayoutParams loadMoreP = new LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
            mLoadMoreLayout.setLayoutParams(loadMoreP);
            mLoadMoreLayout.setOrientation(LinearLayout.VERTICAL);
            this.mContentLayout.addView(mLoadMoreLayout);
        }
    }

    //滚动监听
    protected <T extends AutoLoadScrollListener> void addOriginScrollListener(T t) {
        mRecyclerView.addOnScrollListener(t);
    }

    //移除监听
    protected <T extends AutoLoadScrollListener> void removeOriginScrollListener(T t) {
        mRecyclerView.removeOnScrollListener(t);

    }

    @Override
    protected void onDetachedFromWindow() {
        if (mLoadMoreLayout != null) {
            mLoadMoreLayout.clearAnimation();
            mLoadMoreLayout.removeAllViews();
        }
        if (mRecyclerView != null) {
            removeOriginScrollListener(mAutoLoadScrollListener);
            mRecyclerView.removeAllViews();
        }
        mAutoLoadScrollListener = null;
        this.removeAllViews();
        if (mMessageHandler != null) {
            mMessageHandler.removeCallbacksAndMessages(null);
        }
        removeScrollListener();
        super.onDetachedFromWindow();
    }

    //开始刷新
    public void refresh() {
        if (mSwipeLayout != null) {
            mSwipeLayout.setRefreshing(true);
        }
    }

    //设置进度条颜色
    public void setProgressColor(int... colors) {
        if (mSwipeLayout != null) {
            mSwipeLayout.setColorSchemeResources(colors);
        }
    }

    //设置进度条圈圈的背景色
    public void setProgressBg(int color) {
        if (mSwipeLayout != null) {
            mSwipeLayout.setProgressBackgroundColorSchemeColor(color);
        }
    }

    //设置进度圈大小
    public void setProgressSize(int size) {
        if (mSwipeLayout != null) {
            mSwipeLayout.setSize(size);
        }
    }

    //设置recyclerview样式
    public void setLayoutManager(RecyclerView.LayoutManager layoutManager) {
        if (mRecyclerView != null) {
            mRecyclerView.setLayoutManager(layoutManager);
        }
    }

    public void setItemDecoration(RecyclerView.ItemDecoration itemDecoration) {
        if (mRecyclerView != null && itemDecoration != null) {
            mRecyclerView.addItemDecoration(itemDecoration);
        }
    }

    //设置adapter
    public <T extends RecyclerView.Adapter> void setAdapter(T t) {
        if (mRecyclerView != null) {
            mRecyclerView.setAdapter(t);
        }
    }

    //设置下拉刷新状态
    public void setRefreshStatus(final boolean status) {
        setRefreshStatusDelay(status, 1);
    }

    //设置下拉刷新状态__延时
    public void setRefreshStatusDelay(final boolean status, int delay) {
        mMessageHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (mSwipeLayout != null) {
                    mSwipeLayout.setRefreshing(status);
                }
                if (!status) {
                    isScrollTAG = false;
                    showLoadMoreView(false);
                }
                if (status) {
                    if (mScrollListener != null) {
                        setPage(0);
                        mScrollListener.refresh();
                    }
                }
            }
        }, delay);
    }

    //recyclerview滑动监听
    public class AutoLoadScrollListener extends RecyclerView.OnScrollListener {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
            if (layoutManager != null) {
                totalCount = layoutManager.getItemCount();
            }
            // 找到最后一个完全可见项的位置
            if (layoutManager instanceof StaggeredGridLayoutManager) {
                StaggeredGridLayoutManager manager = (StaggeredGridLayoutManager) layoutManager;
                if (lastVisiblePosition == null) {
                    lastVisiblePosition = new int[manager.getSpanCount()];
                }
                manager.findLastCompletelyVisibleItemPositions(lastVisiblePosition);
                lastItemPosition = getMaxPosition(lastVisiblePosition);
            } else if (layoutManager instanceof GridLayoutManager) {
                lastItemPosition = ((GridLayoutManager) layoutManager).findLastCompletelyVisibleItemPosition();
            } else if (layoutManager instanceof LinearLayoutManager) {
                lastItemPosition = ((LinearLayoutManager) layoutManager).findLastCompletelyVisibleItemPosition();
            } else {
                throw new RuntimeException("Unsupported LayoutManager.");
            }
            Log.d("TAG", "Total count: " + totalCount + " lastItemPosition\t" + lastItemPosition);
            if (lastItemPosition != 0 && totalCount != 0) {
                if (isScrollTAG) {
                    if (!isDragLoadMore && lastItemPosition < totalCount - 1) {
                        Log.d("TAG", "需要收缩加载更多");
                        showLoadMoreView(false);
                    } else if (isDragLoadMore && lastItemPosition == totalCount - 1) {
                        Log.d("TAG", "需要显示加载更多");
                        showLoadMoreView(true);
                    }
                }
            }
        }

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            switch (newState) {
                case SCROLL_STATE_IDLE:
                    RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                    //通过比对 最后完全可见项位置 和 总条目数，来判断是否滑动到底部
                    int visibleItemCount = layoutManager.getChildCount();
                    int totalItemCount = layoutManager.getItemCount();
                    if (visibleItemCount > 0 && lastItemPosition >= totalItemCount - 1 && !isScrollTAG && isDragLoadMore) {
                        isScrollTAG = true;
                        if (mScrollListener != null && mCanLoadMore) {
                            //显示底部布局，并且再次滚动到底部
                            showLoadMoreView(true);
                            //回调监听
                            mScrollListener.loadMore(curPage);
//                            //设置下次触发刷新的时间
//                            mMessageHandler.postDelayed(new Runnable() {
//                                @Override
//                                public void run() {
//                                    isScrollTAG = false;
//                                    showLoadMoreView(false);
//                                }
//                            }, mLoadMoreTime);
                        }
                    }
                    RecyclerNoScroll();
                    break;
                case SCROLL_STATE_DRAGGING:
                    RecyclerScroll();
                    break;
                case SCROLL_STATE_SETTLING:
                    RecyclerScroll();
                    break;
            }
        }
    }

    //显示底部布局，并且再次滚动到底部
    private void showLoadMoreView(boolean isShow) {
        if (isShow) {
            mLoadMoreLayout.setVisibility(VISIBLE);
            mLoadMoreLayout.post(new Runnable() {
                @Override
                public void run() {
                    if (loadMoreViewHeight == 0) {
                        loadMoreViewHeight = mLoadMoreLayout.getMeasuredHeight();
                    }
                }
            });
            if (loadMoreViewHeight == 0) {
                mLoadMoreLayout.animate().alpha(1f).setDuration(200).start();
            } else {
                mLoadMoreLayout.animate().alpha(1f).scaleY(1).setDuration(200).start();
            }
            if (mRecyclerView != null && mRecyclerView.getAdapter() != null) {
                mRecyclerView.smoothScrollToPosition(mRecyclerView.getAdapter().getItemCount());
            }
        } else {
            mLoadMoreLayout.animate().alpha(0.5f).scaleY(0).setDuration(100).start();
            mLoadMoreLayout.setVisibility(GONE);
        }
    }

    private int getMaxPosition(int[] positions) {
        int max = positions[0];
        for (int i = 1; i < positions.length; i++) {
            if (positions[i] > max) {
                max = positions[i];
            }
        }
        return max;
    }

    //设置能否下拉刷新__默认可以
    public void canRefresh(boolean mCanRefresh) {
        this.mCanRefresh = mCanRefresh;
        if (mSwipeLayout != null) {
            mSwipeLayout.setEnabled(this.mCanRefresh);
        }
    }

    //设置能否加载更多__默认可以
    public void canLoadMore(boolean mCanLoadMore) {
        this.mCanLoadMore = mCanLoadMore;
    }

    //设置加载更多时显示的view
    public void setLoadMoreView(View view) {
        if (view == null) return;
        if (mLoadMoreLayout != null) {
            mLoadMoreLayout.addView(view);
            LayoutParams mLMP = (LayoutParams) view.getLayoutParams();
            mLMP.width = LayoutParams.MATCH_PARENT;
            if (mLMP.height == LayoutParams.MATCH_PARENT) {
                mLMP.height = LayoutParams.WRAP_CONTENT;
            }
            view.setLayoutParams(mLMP);
            mLoadMoreLayout.setAlpha(0.5f);
            mLoadMoreLayout.setVisibility(GONE);
        }
    }

//    //设置下拉刷新时显示的view
//    public void setRefreshView(View view) {
//        if(view == null)return;
//        if(mRefreshLayout!=null){
//            mRefreshLayout.addView(view);
//            LinearLayout.LayoutParams mLMP = (LayoutParams) view.getLayoutParams();
//            mLMP.width = LayoutParams.MATCH_PARENT;
//            mLMP.height = LayoutParams.WRAP_CONTENT;
//            view.setLayoutParams(mLMP);
//            mRefreshLayout.setVisibility(GONE);
//        }
//    }

    //用户没有滑动
    void RecyclerNoScroll() {

    }

    //用户滑动
    void RecyclerScroll() {

    }

    /**
     * 设置页数
     */
    public void setPage(int curPage) {
        this.curPage = curPage;
    }

    public RecyclerView getRecyclerView() {
        return mRecyclerView;
    }

    public interface OnScrollListener {
        void loadMore(int nextPage);

        void refresh();
    }

    //滑动的监听
    public void setOnScrollListener(OnScrollListener onScrollListener) {
        this.mScrollListener = onScrollListener;
    }

    private void removeScrollListener() {
        this.mScrollListener = null;
    }
}
